// pages/index/index.js
var app = getApp()


Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab: 1,
    cateActive: 0,
    swiperList: [],
    cateList: [],
    productList: [],
    type: 'doing',
    category_id: 0,
    page: 1,
    endTime: '00:00:00',
    leader: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**,
   * 
   * 
   */
  onShareAppMessage: function() {
    return {
      title: "喵鲜团1元秒杀进行中",
      imageUrl: "/images/share_img.jpg"
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    that.setData({
      category_id: 0,
      cateActive: 0,
      type: 'doing',
      tab:1
    })
    if (that.data.page != 1) {
      that.setData({
        page: 1,
      })
    }
    that.getAllData(that.data.type, that.data.category_id, 1)
  },

  /**
   * 上拉刷新
   */
  onPullDownRefresh: function() {
    let that = this
    wx.showNavigationBarLoading()
    that.getAllData(that.data.type, that.data.category_id, that.data.page)
    wx.hideNavigationBarLoading()
    wx.stopPullDownRefresh()
  },

  /**
   * onReachBottom
   */
  onReachBottom: function() {
    let that = this,
      page = that.data.page
    page = page + 1
    that.setData({
      page: page
    })
    that.getAllData(that.data.type, that.data.category_id, that.data.page)
  },

  /**
   * 获取数据
   */
  getAllData: function(type, cat_id, page) {
    let that = this,
      cats = [],
      pros = [],
      prosed = [],
      pl = that.data.productList,
      data, i, j
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/api/v1/index/index?access_token=' + accessToken,
        data: {
          type: type,
          category_id: cat_id,
          page: page
        },
        success: res => {
          data = res.data.data
          if (res.data.status === 1) {
            if (data.selected.leader_name == "") {
              wx.showModal({
                showCancel: false,
                title: '提示',
                content: '当前团长身份失效，请重新选择团长',
                success: res => {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '../community/community',
                    })
                  }
                }
              })
            }
            if (page == 1) {
              for (i = 0; i < data.cats.length; i++) {
                cats.push({
                  id: data.cats[i].id,
                  name: data.cats[i].name
                })
                for (j = 0; j < data.cats[i].goodses.length; j++) {
                  pros.push(data.cats[i].goodses[j])
                }
              }
              that.setData({
                swiperList: data.ads,
                cateList: cats,
                productList: pros,
                leader: data.selected
              })
            } else {
              for (i = 0; i < data.cats.length; i++) {
                for (j = 0; j < data.cats[i].goodses.length; j++) {
                  pl.push(data.cats[i].goodses[j])
                }
              }
              that.setData({
                productList: pl
              })
            }
            that.endTime()
            wx.hideLoading()
          }
        }
      })
    })
  },

  /**
   * 正在抢购 & 即将开始
   */
  tabChange: function(e) {
    let that = this,
      tb = e.currentTarget.dataset.tb
    if (tb == 1) {
      this.setData({
        type: 'doing',
        tab: tb,
        cateActive: 0,
      })
    } else {
      this.setData({
        type: 'coming',
        tab: tb,
        cateActive: 0,
      })

    }
    that.getAllData(that.data.type, 0, 1)
  },

  /**
   * 热门分类
   */
  cateClick: function(e) {
    let that = this,
      cat_id = that.data.cateList[e.detail.index].id
    that.setData({
      cateActive: cat_id,
      category_id: cat_id,
      page: 1
    })
    that.getAllData(that.data.type, cat_id, 1)
  },

  /**
   * 根据id跳转商品详情
   */
  goProDetail: function(e) {
    let gid = e.currentTarget.id
    wx.navigateTo({
      url: '../product/product?gid=' + gid
    })
  },

  /**
   * 添加购物车
   */
  addCart: function(e) {
    let that = this,
      pid = e.currentTarget.id
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function(accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/api/v1/cart/add?access_token=' + accessToken,
        method: 'POST',
        data: {
          goods_id: pid,
          num: 1
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          if (res.data.status === 1) {
            wx.showToast({
              icon: 'none',
              title: '加入购物车成功',
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
            })
          }
        }
      })
    })
  },

  /**
   * 返回社区选择
   */
  backCommunity: function() {
    wx.navigateTo({
      url: '../community/community?is_back=1',
    })
  },

  /**
   * 倒计时
   */
  endTime: function() {
    let that = this,
      timestamp = Date.parse(new Date()),
      endTime, time, k
    if (that.data.productList.length !== 0) {
      endTime = that.data.productList[0].assemble_end_time * 1000
      time = endTime - timestamp
      that.getLocalTime(time)
      setTimeout(function() {
        that.endTime()
      }, 1000)
      // for(k in that.data.productList) {
      //   if (that.data.productList[k].goods_number !== 0) {
      //     endTime = that.data.productList[0].assemble_end_time * 1000
      //     time = endTime - timestamp
      //     that.getLocalTime(time)
      //     setTimeout(function () {
      //       that.endTime()
      //     }, 1000)
      //   }
      // }
    }
  },

  /**
   * 时间戳转为为普通日期格式
   */
  getLocalTime: function(timestamp) {
    let that = this,
      days = Math.floor(timestamp / (24 * 3600 * 1000)),
      dh = days * 24,
      lv1 = timestamp % (24 * 3600 * 1000),
      h = Math.floor(lv1 / (3600 * 1000)),
      lv2 = lv1 % (3600 * 1000),
      m = Math.floor(lv2 / (60 * 1000)),
      lv3 = lv2 % (60 * 1000),
      s = Math.floor(lv3 / 1000)
    // if (dh == 0) {
    //   that.setData({
    //     endTime: '0' + h + ':' + m + ':' + s
    //   })
    // } else {
    //   that.setData({
    //     endTime: dh + h + ':' + m + ':' + s
    //   })
    // }
    that.setData({
      endTime: dh + h + ':' + m + ':' + s
    })
  }
})